<!--
 * @Description: 生长记录管理页面
-->
<template>
  <BaseMainSlot>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="36"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :cancel-active="cancelActive"
        :save-active="saveActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        :has-edit-column="true"
        :has-export="true"
        @showColumn="showColumn"
        @download="download"
        @add="add"
        @cancel="cancel"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm :formConfig="formConfig" :formData="searchlist" @search="search"></SearchForm>
    </template>
    <template v-slot:table-box>
      <Table @sortChange="changeTableSort" :propList="tableColumn" v-loading="loading"
        :listData="tableData" @handleSelectionChange="handleSelectionChange" :toolTip="false" :key="itemKey">
        <template v-slot:operation="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <el-button
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row)"
            >
              <i class="el-icon-view"></i> 查看详情
            </el-button>
            <el-button
              v-if="judgePermission(36, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="handleEdit(row, 'edit')"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(36, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </template>
        <template v-slot:lesseeName="{ row }">
          <template v-if="!row.index && row.growthProcessRecordNo">
            <span>{{ row.lesseeName ? row.lesseeName : "—" }}</span>
          </template>
        </template>
        <template v-slot:collectTime="{ row }">
          <template v-if="!row.index && row.collectTime">
            {{ goTime(row.collectTime) }}
          </template>
        </template>
        <template v-slot:pictureNoList="{ row,index }">
          <!-- <template v-if="!row.index && row.growthProcessRecordNo">
            <el-button
              v-if="row.pictureNoList.length"
              type="success"
              @click="getpicmessage(row.pictureNoList)"
            >点击查看</el-button>
            <span v-else>暂无图片</span>
          </template> -->
          <template v-if="!row.index && row.growthProcessRecordNo">
            <div v-if="row.pictureNoList.length" class="viewImgContainer">
              <div class="viewImg" @click="getpicmessage(row.pictureNoList,index)">
                <img
                  class="viewImg"
                  v-show="row.viewImg"
                  src="@/assets/unifiedPicture/viewImg1.png"
                />
              </div>
            </div>
            <el-button v-else type="text" disabled
              >{{ row.index }}暂无图片</el-button
            >
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="dialogTitle + '生长记录信息'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
        width="40%"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          :show-message="isshowrulemessage"
          class="el-form"
        >
        <el-form-item label="设施选择:" prop="facilityNo" class="w50p">
            <el-select
              v-model="formData.facilityNo"
              @change="changeFacilityNo"
              clearable
              :disabled="!nowChanceStau"
            >
              <el-option
                v-for="(item, index) in facilityList"
                :key="index"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="批次名称:" prop="batchNo" class="w50p">
            <el-select v-model="formData.batchNo" :disabled="!nowChanceStau" filterable clearable>
              <el-option
                v-for="(item, index) in batchAList"
                :key="index"
                :label="item.batchName"
                :value="item.batchNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="记录标题:" prop="recordTitle" class="w50p">
            <el-input v-model="formData.recordTitle" :disabled="!nowChanceStau" clearable />
          </el-form-item>
          <el-form-item label="阶段选择:" class="w50p" prop="growthPhaseNo">
            <el-select v-model="formData.growthPhaseNo" :disabled="!nowChanceStau" clearable>
              <el-option
                v-for="(item, index) in growthPhasList"
                :key="index"
                :label="item.growthPhaseName"
                :value="item.growthPhaseNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="生长速度:" prop="growthSpeed" class="w50p">
            <el-select
              v-model="formData.growthSpeed"
              class="inline-input"
              filterable
              clearable
              :disabled="!nowChanceStau"
              placeholder="请选择生长速度"
              @change="handleSelect"
            >
              <el-option
                v-for="(item, index) in restaurants"
                :key="index"
                :value="item.name"
                :label="item.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="记录图片:"
            prop="weChat"
            class="w100p"
          >
            <ele-upload-image
              v-if="dialogFormVisible"
              multiple
              v-model="nowsectpictureidtwo"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :action="ImageUrl()"
              :class="{ disabled: !nowChanceStau }"
            />
          </el-form-item>
          <el-form-item :label="'是否有' + farmingTypeTitles + ':'" class="w50p">
            <el-select v-model="formData.whetherPests" :disabled="!nowChanceStau" clearable>
              <el-option
                v-for="(item, index) in whetherPestsList"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests"
            :label="farmingTypeTitles + '描述:'"
            prop="weChat"
            class="w50p"
          >
            <el-input v-model="formData.description" :disabled="!nowChanceStau" clearable />
          </el-form-item>
          <el-form-item
            v-if="formData.whetherPests"
            :label=" farmingTypeTitles + '图片:'"
            prop="weChat"
            class="w50p"
          >
            <ele-upload-image
              v-if="dialogFormVisible"
              v-model="nowsectpictureid"
              :response-fn="handleResponse2"
              :before-remove="handleRemove2"
              :headers="headers"
              :action="ImageUrl()"
              :class="{ disabled: !nowChanceStau }"
            />
          </el-form-item>
          <el-form-item label="记录信息:" prop="remark" class="w50p">
            <el-input v-model="formData.remark" :disabled="!nowChanceStau" clearable />
          </el-form-item>
          <el-form-item
            v-if="nowChanceStau === 'edit' || nowChanceStau === 'add'"
            label="物联数据:"
            class="w50p"
            prop="date1"
          >
            <el-date-picker
              v-model="zhdateList"
              align="right"
              type="date"
              :disabled="!nowChanceStau"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptionsone"
              @change="getdataitemlist"
            />
          </el-form-item>
          <el-form-item v-if="zhdateList" label="物联数据展示:" class="checklinesty">
            <el-checkbox
              v-model="checkAll"
              :disabled="!nowChanceStau"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >全选</el-checkbox>
            <div style="margin: 0px 10px"></div>
            <el-checkbox-group
              v-if="dataCities"
              v-model="checkedCities"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="(dataItem, datindex) in dataItemList"
                :key="'check' + datindex"
                :label="dataItem.dataItemId"
              >{{ dataItem.dataItemName }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
      <el-dialog title="图片:" :visible.sync="showpicview" width="30%" @close="closeViewImg">
        <img
          v-for="item,i in pictviewurl"
          :key="i"
          style="width: 80%; max-height: 500px; margin-left: 10%"
          :src="item"
        />
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="showpicview = false">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="showpicview = false"
          >确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="dialogTableColumnVisible = false">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="saveColumn"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import SearchForm from '@/components/searchForm';
import Table from '@/components/table/table.vue';
import uploadimage from "../uploadimage/uploadimage.vue";
import uploadimages from "../uploadimage/uploadimages.vue";
import facgroupreq from "@/api/user/index";
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import nowpagereq from "@/api/digital-production/growth-record-management/growth-record-managementtwo";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import tenantInfo from "@/api/digital-operation/tenant-manage/tenant-info/index";
import { mymixin } from "@/utils/mixin";
import { getToken } from "@/utils/auth";
import { mapGetters } from "vuex";
import { farmingTypeTitle } from "@/utils/validate";
import baseURL from "@/api/baseURL";
export default {
  name: "GrowthRecordManagementtwo",
  components: {
    SearchForm,
    Table,
    ActionBar,
    Pagination,
    BaseMainSlot,
    uploadimage,
    uploadimages
  },
  mixins: [mymixin],
  data() {
    var checkdate = (rule, value, callback) => {
      // 在外面,不能用length
      // console.log(this.zhdateList)
      if (this.zhdateList === "" || this.zhdateList === null) {
        callback(new Error("请选择时间"));
      } else {
        // console.log(this.zhdateList)
        setTimeout(() => {
          callback();
        }, 1000);
      }
    };
    return {
      itemKey: '',
      tableColumn: [
        { prop: 'batchName', label: '批次名称' },
        { prop: 'batchNo', label: '批次号' },
        { prop: 'lesseeName', label: '种植户', slotName: 'lesseeName' },
        { prop: 'recordTitle', label: '记录标题' },
        { prop: 'collectTime', label: '记录时间', slotName: 'collectTime', width: '160' },
        { prop: 'remark', label: '记录信息' },
        { prop: 'pictureNoList', label: '查看图片', slotName: 'pictureNoList' },
        { prop: 'operation', label: '操作', slotName: 'operation', width: '220' }
      ],
      formConfig: [
        {
          label: '选择批次',
          prop: 'batchNo',
          type: 'select',
          options: [], // batchList
          optionKey: { label: 'batchName', value: 'batchNo' },
        }, {
          label: '选择设施',
          prop: 'facilityNo',
          type: 'select',
          options: [], // facilityList
          optionKey: { label: 'facilityName', value: 'facilityNo' }
        }, {
          label: '承租户',
          prop: 'lesseeNo',
          type: 'select',
          options: [], // lesseeList
          optionKey: { label: 'lesseeName', value: 'lesseeNo' }
        }, {
          label: '选择时间',
          prop: 'date',
          type: 'daterange',
        },
      ],
      isshowrulemessage: false,
      // 图片弹框
      showpicview: false,
      farmingTypeTitles: farmingTypeTitle(),
      pictviewurl: [],
      // 多选框相关
      checkAll: true,
      checkedCities: [],
      isIndeterminate: true,
      // 当前选中的记录图片id
      nowsectpictureidtwo: [],
      recordPictureNoList: [],
      // 当前物联数据日期选择
      zhdateList: "",
      dataItemList: [],
      // 当前选中的病虫害图片id
      nowsectpictureid: '',
      pestPictureNo: '',
      // 生长阶段
      restaurants: [],
      batchAList: [],
      lesseeNo: "",
      lesseeList: [],
      state1: "",
      // 是否有病虫害
      whetherPestsList: [
        { name: "是", value: true },
        { name: "否", value: false }
      ],
      // 可选择批次列表
      batchList: [],
      // 可选择所有地块
      facilityList: [],
      // 获取所有生长阶段
      growthPhasList: [],
      // 一般为农业类型id
      farmingTypeNo: "",
      // 所搜索框内容
      searchlist: {
        batchNo: "",
        facilityNo: "",
        dateList: []
      },
      pickerOptionsone: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", new Date());
            }
          },
          {
            text: "昨天",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周前",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      dataItemCities: [],
      dataCities: false,
      // 新增校验条件
      rules: {
        recordTitle: [
          { required: true, message: "请输入记录标题", trigger: "blur" },
          // { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        batchNo: [{ required: true, message: "请选择批次", trigger: "change" }],
        facilityNo: [
          { required: true, message: "请选择设施", trigger: "change" }
        ],
        growthPhaseNo: [
          { required: true, message: "请选择生长阶段", trigger: "change" }
        ],
        growthSpeed: [
          { required: true, message: "请选择生长速度", trigger: "change" }
        ],
        // remark: [
        //   { required: true, message: "请输入记录信息", trigger: "blur" }
        // ],
        date1: [
          { required: true, validator: checkdate, trigger: ["change", "blur"] }
        ]
      },
      dialogTitle: "",
      dialogFormVisible: false
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {
    nowChanceStau(newval) {
      this.nowsectpictureidtwo = []
      // this.recordPictureNoList = []
      this.nowsectpictureid = ''
      this.pestPictureNo = ''
      this.getselectdatalist();
      if (newval === "add") {
        // managementtwo.queryBatchList().then(res => {
        //   this.batchList = res.data;
        // });
        this.zhdateList = "";
        // this.formData.whetherPests = false;
        this.$set(this.formData, "whetherPests", false);
      }
      if (newval === "") {
        this.isshowrulemessage = false;
      } else {
        this.isshowrulemessage = true;
      }
    },
    dialogFormVisible(v) {
      if (v) {
        this.$nextTick(()=>{
          this.$refs.formData.clearValidate()
        })
      }
    }
  },
  created() {},
  mounted() {
    this.chancefarmtype(getToken("farmingTypeNo"));
    this.restaurants = this.loadAll();
  },
  methods: {
    // 下拉可选择数据
    async getselectmessage() {
      // 获取所有批次选择框数据
      managementtwo.queryBatchListName().then(res => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
    },
    // 设施选择
    async changeFacilityNo(e) {
      // this.formData.batchNo = [];
      this.batchAList = []
      let params = {
        no: e,
        batchStatus: 0,
      };
      let res = await managementtwo.accordPlotGetBatch(params);
      this.batchAList = res.data;
      this.$set(this.formData, 'batchNo', '');
      this.zhdateList && this.getdataitemlist();
    },
    changebatchid(id) {
      // 获取设施选择框数据 queryFacilityListName
      let list = this.batchList.filter(item => item.batchNo === id);
      if (list[0].lesseeNo) {
        this.$set(this.formData, "lesseeNo", list[0].lesseeNo);
      }
      // console.log(this.formData)
      managementtwo.getbatchfaclist(id).then(res => {
        this.facilityList = res.data;
        this.formConfig[1].options = res.data;
        // this.batchList(item => {
        //   if(id === item.)
        // })
        if (id) {
          nowpagereq.getByBatchNoPhasList(id).then(res => {
            this.growthPhasList = res.data;
          });
        }
      });
    },
    // 获取图片详情
    async getpicmessage(idlist,index) {
      this.tableData.forEach((el) => {
        el["viewImg"] = false;
      });
      this.$set(this.tableData[index], "viewImg", true);
      this.showpicview = true;
      idlist?.length && idlist.map((el, i) => {
        this.recordPictureNoList.push(el)
        nowpagereq.growthProcessPicture(el).then(res => {
          this.$set(this.pictviewurl, i,"data:image/png;base64," + res.data.pictureData)
        });
      })
      // let id = idlist[0];
      // if (id) {
      //   let res = await nowpagereq.growthProcessPicture(id);
      //   this.pictviewurl = `data:image/png;base64, ${res.data.pictureData}`;
      // } else {
      //   this.$message.warning("暂无图片信息！");
      // }
    },
    // 时间戳展示正常时间
    goTime(val) {
      var timestamp4 = new Date(val);
      // 利用拼接正则等手段转化为yyyy-MM-dd HH:mm:ss 格式
      return (
        timestamp4.toLocaleDateString().replace(/\//g, "-") +
        " " +
        timestamp4.toTimeString().substr(0, 8)
      );
    },
    // 多选框选择方法
    handleCheckAllChange(val) {
      // console.log(val)
      if (val) {
        this.checkedCities = this.dataItemList.map(item => item.dataItemId);
        this.handleCheckedCitiesChange(this.checkedCities);
      } else this.checkedCities = [];
      // this.checkedCities = val ? this.dataItemList.map(
      //   item => item.dataItemId
      // ) : [];
      this.isIndeterminate = false;
      // console.log(this.checkedCities)
    },
    handleCheckedCitiesChange(newlist) {
      // let value = this.checkedCities
      // console.log(value)
      let checkedCount = newlist.length;
      // this.checkAll = checkedCount === this.dataItemList.length;

      // 更改
      // if (this.checkedCities.length > 0) this.checkAll = true;
      // else this.checkAll = false;
      // console.log(this.checkAll)
      this.dataItemCities = [];
      // if (this.checkAll) {
      this.dataItemList.forEach(dataItem => {
        newlist.forEach(Cities => {
          if (dataItem.dataItemId === Cities) {
            this.dataItemCities.push(dataItem);
          }
        });
      });
      // }
      if (checkedCount === this.dataItemList.length) {
        this.checkAll = true;
      } else {
        this.checkAll = false;
      }
      // this.dataItemCities = []
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.dataItemList.length;
    },
    // 图片地址
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        return `${baseURL.webServiceUrl}v3/growth/growthProcessPicture/add`;
      } else {
        return "#";
      }
    },
    handleResponse(res) {
      this.recordPictureNoList.push(res.data.pictureNo)
      return "data:image/png;base64," + res.data.pictureData;
    },
    handleRemove(row) {
      console.log(row)
      let index = this.nowsectpictureidtwo.findIndex(el => { return el === row })
      console.log(index)
      this.recordPictureNoList.splice(index, 1)
      console.log(this.recordPictureNoList)
    },
    // 图片地址
    ImageUrl2() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        return `${baseURL.webServiceUrl}v3/growth/growthProcessRecordPestsPicture/add`;
      } else {
        return "#";
      }
    },
    handleResponse2(res) {
      this.pestPictureNo =res.data.pictureNo
      return "data:image/png;base64," + res.data.pictureData;
    },
    handleRemove2() {
      this.pestPictureNo = ''
      this.nowsectpictureid = ''
    },
    // 输入建议
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return restaurant => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    loadAll() {
      return [
        { name: "正常", value: 0 },
        { name: "快", value: 1 },
        { name: "过快", value: 2 },
        { name: "慢", value: 3 },
        { name: "过慢", value: 4 }
      ];
    },
    handleSelect(item) {
      // console.log(this.state1);
      // console.log(item);
    },

    // ----
    // 在有农业类型的页面中以此方法为获取表格方法
    chancefarmtype(e) {
      this.getselectdatalist();
      this.farmingTypeNo = e;
      // 获取表格数据
      this.getTableDataList();
      this.tableData = [];
    },
    // 获取下拉框数据
    async getselectdatalist() {
      // 获取所有地块
      let faciparams = {};
      if (this.nowChanceStau === "add") {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          // facilityStatus: 1
        };
      } else {
        faciparams = {
          organizationList: sessionStorage
            .getItem("organizationList")
            .split(","),
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo")
        };
      }
      facgroupreq.getfacilityAll(faciparams).then(res => {
        this.facilityList = res.data;
        this.formConfig[1].options = res.data;
      });
      let param = {};
      if (this.nowChanceStau === "add") {
        param = {
          farmingTypeNo: sessionStorage.farmingTypeNo,
          status: 0
        };
      } else {
        param = {
          farmingTypeNo: sessionStorage.farmingTypeNo
        };
      }
      // 获取所有批次
      nowpagereq.getallbatchList(param).then(res => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      // 获取所有生长阶段
      nowpagereq.getallgrowthPhasList().then(res => {
        this.growthPhasList = res.data;
      });

      // 做不同的请求获取数据
      // 获取承租人下拉框
      const { data: lessee } = await tenantInfo.queryLessesByCondition();
      this.lesseeList = lessee;
      this.formConfig[2].options = lessee;
    },
    // 导出
    async download() {
      let params = {
        entity: {
          ...this.entity,
        }
      }
      let url = 'v3/growth/growthProcessRecord/download'
      let excel = '生长记录表'
      this.downloadExcel(url, params, excel)
    },
    // 表格查询
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        sortList: this.sortList || [],
        entity: {
          batchNo: this.searchlist.batchNo || undefined,
          lesseeNo: this.searchlist.lesseeNo || undefined,
          facilityNo: this.searchlist.facilityNo || undefined,
          farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
          organizationNo: sessionStorage.getItem("organizationNo"),
          endTime: this.searchlist.date
            ? this.dateToFormat(this.searchlist.date[1])
            : undefined,
          startTime: this.searchlist.date
            ? this.dateToFormat(this.searchlist.date[0])
            : undefined
        }
      };
      this.entity = params.entity
      nowpagereq.getlist(params).then(res => {
        this.loading = false;
        if (res.code === 1) {
          // this.$message.success('查询成功')
        } else {
          this.$message.error("查询失败");
        }
        let data = res.data.content;
        // 赋值总条数
        this.totalSize = res.data.totalElements;
        // 赋值数组
        this.tableData = data;
        this.tableData.forEach(el=>{
          el['viewImg'] = false
        })
        this.addblankmet();
        this.dataCities = false;
      });
      // 判断搜索输入框数据
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    add() {
      this.addActive = false;
      this.formData = {};
      this.checkAll = false;
      this.checkedCities = [];
      // this.$set(this.checkedCities, [])
      this.openDialog("add");
    },
    async handleEdit(row, type) {
      console.log(row)
      this.cancel();
      if (row.indflag) {
        this.$message.warning("请勿选择空数据");
        return;
      }
      managementtwo.queryBatchListName().then(res => {
        this.batchList = res.data;
        this.formConfig[0].options = res.data;
      });
      this.dataCities = true;
      let res = await nowpagereq.queryByNo(row.growthProcessRecordNo);
      row = res.data;
      // 图片
      this.recordPictureNoList = []
      this.nowsectpictureidtwo = []
      row.recordPictureNoList?.length && row.recordPictureNoList.map((el, i) => {
        this.recordPictureNoList.push(el)
        nowpagereq.growthProcessPicture(el).then(res => {
          this.$set(this.nowsectpictureidtwo, i,"data:image/png;base64," + res.data.pictureData)
        });
      })
      console.log(this.recordPictureNoList)
      this.pestPictureNo = ''
      this.nowsectpictureid = ''
      row.pestPictureNo && nowpagereq.growthProcessPicture(row.pestPictureNo).then(res => {
        this.nowsectpictureid = "data:image/png;base64," + res.data.pictureData
      });
      this.pestPictureNo = row.pestPictureNo

      this.formData = res.data;
      if (row.growthProcessRecordPests) {
        this.formData.result = row.growthProcessRecordPests.result;
        this.formData.description = row.growthProcessRecordPests.description;
      }
      this.formData.facilityNo = row.facilityNoList[0];
      this.facilityNoList = row.facilityNoList;
      this.checkedCities = row.growthProcessRecordDataCollectList.map(item => {
        return item.dataItemId;
      });
      // collectTime
      // facilities.facilityNo
      this.dataItemList = row.growthProcessRecordDataCollectList;

      this.openDialog(type);
    },
    handleSelectionChange(list) {
      this.nowSelectList = [];
      let notvalue = true;
      // console.log(list);
      this.nowSelectList = list.map(item => {
        if (item.growthProcessRecordNo) {
          return item.growthProcessRecordNo;
        } else {
          notvalue = false;
          return "";
        }
      });
      if (notvalue === false) {
        this.$message.warning("不可选择空数据！");
        return;
      }
      if (this.nowSelectList.length >= 1) this.delActive = true;
      else this.delActive = false;
    },
    // 取消
    cancel() {
      this.addActive = true;
      // 获取所有生长阶段
      nowpagereq.getallgrowthPhasList().then(res => {
        this.growthPhasList = res.data;
      });
      
      // this.nowChanceStau = 'cancel'
      this.nowChanceStau = "";
      this.formData = {};
      this.closeDialog();
    },
    // 删除时触发方法
    delmessage() {
      nowpagereq.dellist(this.nowSelectList).then(res => {
        if (res.code === 1) {
          this.$message.success("删除成功！");
          this.getTableDataList();
        } else {
          this.$message.error("删除失败！");
        }
      });
    },
    handleDelete(data) {
      // nowpagereq.dellist([data.growthProcessRecordNo]).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success("删除成功");
      //     this.getTableDataList();
      //   } else {
      //     this.$message.error("删除失败");
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          nowpagereq.dellist([data.growthProcessRecordNo]).then(res => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    },
    save() {
      this.$refs["formData"].validate(valid => {
        if (valid) {
          // -----保存状态判断-----
          if (this.nowChanceStau === "edit") {
            let editparams = {
              recordTitle: this.formData.recordTitle,
              growthProcessRecordNo: this.formData.growthProcessRecordNo,
              growthPhaseNo: this.formData.growthPhaseNo,
              batchNo: this.formData.batchNo,
              // facilityNo: this.formData.facilityNo,
              growthSpeed: this.formData.growthSpeed,
              whetherPests: this.formData.whetherPests
            };
            if (this.formData.facilityNo) {
              editparams.facilityNoList = [this.formData.facilityNo];
              // delete editparams.facilityNo
            }
            if (this.recordPictureNoList !== "") {
              editparams.recordPictureNoList = this.recordPictureNoList;
            }
            if (this.formData.whetherPests === true) {
              if (this.nowsectpictureid !== "") {
                editparams.pestPictureNo = this.pestPictureNo;
              }
              editparams.description = this.formData.description;
            }
            if (this.checkAll) {
              editparams.growthProcessRecordDataCollectList = this.dataItemCities;
            } else {
              // 根据选中的名字一个找出对应的数据-zz
            }

            // console.log(editparams)
            // return
            nowpagereq.editlist(editparams).then(res => {
              if (res.code === 1) {
                this.$message.success("修改成功！");
                this.closeDialog();
                this.resetActionBar();
                this.getTableDataList();
              } else {
                this.$message.error("修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            // 新增接口
            let newzhdate = Date.parse(new Date());
            let zhparams = {
              ...this.formData,
              collectTime: newzhdate
            };
            if (this.formData.facilityNo) {
              zhparams.facilityNoList = [this.formData.facilityNo];
              delete zhparams.facilityNo;
            }
            if (this.recordPictureNoList !== "") {
              zhparams.recordPictureNoList = this.recordPictureNoList;
            }
            if (this.formData.whetherPests === true) {
              zhparams.pestPictureNo = this.nowsectpictureid;
            }
            if (this.dataItemCities.length > 0) {
              // if (this.checkAll) {
              zhparams.growthProcessRecordDataCollectList = this.dataItemCities;
              // }
            } else {
              // this.$message.warning("请选择物联数据！")
              // return
            }
            // console.log(zhparams)
            // console.log(this.checkAll)
            // return
            nowpagereq.addlist(zhparams).then(res => {
              if (res.code === 1) {
                this.$message.success("添加成功！");
                this.closeDialog();

                this.resetActionBar();
                this.getTableDataList();
              } else {
                this.$message.error("添加失败！");
              }
            });
          }
        } else {
          this.$message.warning("请填写完整！");
        }
      });
    },
    getdataitemlist() {
      let params = {
        date: this.dateToFormat(this.zhdateList),
        facilityNo: this.formData.facilityNo || null
      };
      nowpagereq.getalldataitembydateList(params).then(res => {
        this.dataItemList = res.data;
        let newlist = [];
        if (res.data && res.data.length > 0) {
          res.data.forEach(item => {
            newlist.push(item.dataItemId);
          });
          this.dataItemCities = res.data;
          this.dataCities = true;
        } else {
          this.dataCities = false;
        }
        this.checkedCities = newlist;
      });
    },
    openDialog(type) {
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : (type === "edit" ? "编辑" : '');
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    closeViewImg() {
      this.tableData.forEach((el) => {
        el["viewImg"] = false;
      });
      this.$set(this, "tableData", this.tableData);
      this.itemKey = Math.random()
    }
  }
};
</script>

<style scoped lang="scss">
.checklinesty {
  width: 100% !important;
  // background-color: #85ce61;
}
// ::v-deep .el-checkbox {
// .el-checkbox__label {
// color: #fff;
// flex-direction: column;
// }
// }
::v-deep .el-button--success:hover {
  background: #fff;
  border-color: #fff;
  color: #85ce61;
}
// ::v-deep .common-layout{ .content {.form {.el-form{
//     width: 100%;
//     height: 240px;
//     display: flex;
//     justify-content: flex-start !important;
//     align-items: center;
//     flex-wrap: wrap;
//     flex-direction: column;
//     align-content: space-around;
// }}}}
.viewImgContainer {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  .viewImg {
    width: 80px;
    height: 32px;
    cursor: pointer;
    background: url("~@/assets/unifiedPicture/viewImg-d.png") no-repeat 100%
      100%;
    &:hover {
      background: url("~@/assets/unifiedPicture/viewImg.png") no-repeat 100%
        100%;
    }
  }
}
</style>
